#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务端");
    socket=new QTcpServer(this);               //实例化
    connect(socket,&QTcpServer::newConnection,this,&Widget::processConnect);
//    socket->bind()                             //绑定端口号
    auto ret=socket->listen(QHostAddress::Any,8000);
    //监听失败
    if(!ret){
        QMessageBox::critical(this,"服务器启动失败",socket->errorString());
        exit(1);
    }

}

Widget::~Widget()
{
    delete ui;
   delete socket;
}


////////////////////////////////////////////////////////////////////////////////////////////////////

//处理新链接
void Widget::processConnect(){
    //获取新的套接字
    QTcpSocket* clientSocket=socket->nextPendingConnection();
    QString log="["+clientSocket->peerAddress().toString()+": "+QString::number(clientSocket->peerPort())
            +"]客户端上线";
    ui->listWidget->addItem(log);
    //读取新的数据就计算响应的数据报文,发送回去，并打印日志
    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
        QString request=QString::fromUtf8(clientSocket->readAll());//返回的是字节流
        const QString& response=process(request);
        clientSocket->write(response.toUtf8());

        QString log="["+clientSocket->peerAddress().toString()+": "+QString::number(clientSocket->peerPort())
                +"]req: "+request+" , resp "+response;
        ui->listWidget->addItem(log);

    });
    //断开连接日志
    connect(clientSocket,&QTcpSocket::disconnected,this,[=](){
        QString log="["+clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+
                "]"+"客户端下线了";
//        delete clientSocket;//释放套接字,因为客户端可能会有很多--->内存泄漏,文件描述符
//        close(clientSocket->d);
        ui->listWidget->addItem(log);
        clientSocket->deleteLater();//在下一轮事件循环中进行销毁操作
    });

}

QString Widget::process(const QString&request){
    return request;
}
